package it.afs.worklog.application.form.admin;

import it.afs.worklog.Attivita;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;

/**
 * @author Fanta
 */
public class AttivitaFormPage extends AdminPage
{
	public AttivitaFormPage(PageParameters parameters)
	{
		super(parameters);
		
		if(!parameters.containsKey("id"))
			addComponents(new Attivita(getFactory().getDao().getCommessa(parameters.getString("commessa"))));
		else
			addComponents(getFactory().getDao().getAttivita(parameters.getString("id")));
	}
	
	private void addComponents(Attivita object)
	{
		addComponents();
		
		add(new Link<String>("back", new Model<String>(object.getCommessa().getId()))
		{
			private static final long serialVersionUID = 6446879497706151791L;

			@Override
			public void onClick()
			{
				setResponsePage(AttivitaPage.class, new PageParameters("commessa=" + getModelObject()));
			}
		});
		
		if(object.isNew())
		{
			object.setAttivo(true);
		}
		
		Form<Attivita> form = new Form<Attivita>("form", new CompoundPropertyModel<Attivita>(object))
		{
			private static final long serialVersionUID = 3290765309118472928L;

			@Override
			protected void onSubmit()
			{
				super.onSubmit();
				if(getFactory().getDao().set(getModelObject()))
				{
					setResponsePage(AttivitaPage.class, new PageParameters("commessa=" + getModelObject().getCommessa().getId()));
				}
				else
				{
					error(getString("submit.error"));
				}
			}
		};
		add(form);
		
		form.add(new RequiredTextField<String>("oggetto"));
		form.add(new CheckBox("attivo"));
		
		form.add(new FeedbackPanel("feedback"));
	}
}